// 假设add是个复杂计算函数
const add = function (a) {
    return a + 1
}

// 实现可以缓存其他函数结果的高阶函数
function memorize(fn) {
    const cache = new Map();
    return function (...args) {
        // 创建更可靠的缓存键
        const cacheKey = args.length === 1
            ? args[0]
            : JSON.stringify(args);

        if (cache.has(cacheKey)) {
            console.log('Getting from cache');
            return cache.get(cacheKey);
        }

        console.log('Calculating result');
        const result = fn.apply(this, args);
        cache.set(cacheKey, result);
        return result;
    };
}

///////////////////////////////////////////////

// 通过memorize获得了add的缓存函数 adder；
const adder = memorize(add)
console.log(adder(1))
console.log(adder(1))
console.log(adder(2))

console.log('----------------------------------------')

// 测试复杂参数
const complexAdd = memorize((a, b) => {
    console.log('Calculating...');
    return a.value + b.value;
});

const obj1 = {value: 1};
const obj2 = {value: 2};

console.log(complexAdd(obj1, obj2)); // Calculating..., 输出: 3
console.log(complexAdd(obj1, obj2)); // 从缓存获取, 输出: 3


// function demo(...args){
//     console.log(JSON.stringify(args))
//     let t = JSON.stringify(args);
//     let cache = new WeakMap();
//     cache.set(t, '22222')
// }
// demo({id: 'k23qj4523'},2,3)
// demo(1,2,3)

